"""代码结构调整 未启用; 泛型"""
import logging
from pydantic import BaseModel
from sqlalchemy.orm import Session
from sqlalchemy import func
from sql_app.models import *
from typing import TypeVar, Generic, Sequence
from schemas import *

from sql_app.database import Base

OrmModel = TypeVar("OrmModel", bound=Base)
a = TypeVar("a", bound=int)

logger = logging.getLogger("crud")


# class CrudBase(Generic[OrmModel, a]):
class CrudBase():
    def __init__(self, orm_model: OrmModel):
        self.model = orm_model
        self.max = None

    @property
    def gen_id(self):
        self.max += 1
        return self.max

    def get_max(self, db: Session):
        max_id = db.query(func.max(self.model.id)).scalar()
        self.max = max_id if max_id else 0

    def get_count(self, db: Session):
        return db.query(func.count(self.model.id)).scalar()

    def get_a_batch(
            self, db: Session,
            offset: int = 1,
            limit: int = 30,
            keyword: str = None):
        if keyword is None:
            return db.query(self.model).offset(offset).limit(limit).all()
        else:
            pass

    def get_name_by_id(self, db:Session, vote_id: int):
        detail = self.get_detail(db, vote_id)
        if detail is None:
            pass
        else:
            name = getattr(detail, "name", None)
            return name if name is not None else getattr(res, "title")

    def get_detail(self, db: Session, _id: int):
        detail = db.query(self.model).filter(self.model.id == _id).scalar()

        return detail

    def delete(self, db: Session, model: BaseModel):
        for i, _ids in model:
            for _id in _ids:
                print("删除: ", _id, _ids)
                db.query(self.model).filter(self.model.id == _id).delete()
        db.commit()

    def create(self, db: Session, model: BaseModel):

        schema_model_dict = model.dict(
            exclude={"accesstoken"},
            exclude_none=True)
        if self.max is None:
            self.get_max(db)
        model_id = self.gen_id
        schema_model_dict["id"] = model_id

        db_model = self.model(**schema_model_dict)
        db.add(db_model)
        db.commit()
        db.refresh(db_model)
        return db_model

    def adjust(self, db: Session, model: BaseModel):
        db_model = self.model()

        for key, value in model.dict(exclude_none=True).items():
            setattr(db_model, key, value)

        db.merge(db_model)

        db.commit()

        return db_model
